import Vue from 'vue'
import VueRouter from 'vue-router'

import cartRouter from './modules/cart'
import homeRouter from './modules/home'
import liveRouter from './modules/live'
import mineRouter from './modules/mine'


// 导入模块化后的路由模块文件
import CategoryRoutes from "../router/modules/Category"
import CategoryBuyRoutes from "../router/modules/CategoryBuy"
import DetailRoutes from "../router/modules/Detail"


// 导入 store
import store from '@/store/index'





Vue.use(VueRouter)

const routes = [

  // 重定向路由在默认的时候显示首页的内容
  {
    path: '/',
    redirect: '/home'
  },

  //首页
  ...homeRouter,
  // //直播
  ...liveRouter,
  // //购物车
  ...cartRouter,
  // //我的
  ...mineRouter,

  // 分类模块的路由
  ...CategoryRoutes,

  //分类模块下的购买路由
  ...CategoryBuyRoutes,

  ...DetailRoutes,
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 解决编程式导航重复导航到同一地址报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};


// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 点击购物车和我的页面需要进行判断
  var toPathArr = ['mine', 'cart'];
  var toPath = to.path.split('/')[1];
  // console.log(toPath);
  if (toPathArr.includes(toPath)) {
    // 判断 store 里面 _session
    if (sessionStorage.getItem("session_id")) {
      // 允许跳转到对应的页面
      next();
    } else {
      // 跳转到登录页面，并且将目标路由作为参数携带，方便登录完成后跳转到目标页面
      router.push({
        path: '/login',
        query: { returnUrl: toPath }
      })
    }
  } else {
    next();
  }
})

export default router
